<?php

//No direct acesss
defined('_JEXEC') or die();

jimport('joomla.application.component.model');
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.path');
jimport('joomla.client.helper');
JClientHelper::setCredentialsFromRequest('ftp');

class SimplelistingModelListings extends JModel {

	var $_data = null;
	var $_total = null;
	var $_pagination = null;
	var $_table_prefix = null;


    function __construct()
    {
        parent::__construct();
        $this->_table_prefix = '#__simplelisting';
        $application= JFactory::getApplication();
        $option = JRequest::getCmd( 'option').'-listings';

        $limit	= $application->getUserStateFromRequest( 'global.list.limit', 'limit', $application->getCfg('list_limit'), 'int');
        $limitstart = $application->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );

        $this->setState('limit', $limit);
        $this->setState('limitstart', $limitstart);
    }


    function getData()
    {
        if (empty($this->_data))
        {
            $query = $this->_buildQuery();
            $this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
        }
            return $this->_data;
    }


    function getTotal() {

        if (empty($this->_total)) {
            $query = $this->_buildQuery();
            $this->_total = $this->_getListCount($query);
        }

        return $this->_total;
    }
	

    function getPagination()
    {
            if (empty($this->_pagination))
            {
                    jimport('joomla.html.pagination');
                    $this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
            }

            return $this->_pagination;
    }
  	
    function _buildQuery()
    {
        $where   = $this->_buildContentWhere();
        $orderby = $this->_buildContentOrderBy();

        $query = 'SELECT a.*,
        u.name as `username`, u.email as `email`, u.id as `userid`,
        t.name as `type`, ca.name as `category`, l.name as `layout`,
        cd.telephone as `tel`, cd.mobile `mobile`, cd.fax as `fax`
        FROM '.$this->_table_prefix.' AS a
        LEFT JOIN '.$this->_table_prefix.'_types AS t ON t.id = a.type_id
        LEFT JOIN '.$this->_table_prefix.'_categories AS ca ON ca.id = a.category_id
        LEFT JOIN '.$this->_table_prefix.'_layouts AS l ON l.id = a.layout_id
        LEFT JOIN #__users AS u ON u.id = a.create_by
        LEFT JOIN #__contact_details AS cd ON cd.user_id = a.create_by'
        .$where
        .$orderby;

                return $query;
    }
	
    function _buildContentWhere()
    {
        $application= JFactory::getApplication();
        $option = JRequest::getCmd( 'option').'-listings';
        
        $db                 =& JFactory::getDBO();
        $filter_state       = $application->getUserStateFromRequest($option.'filter_state', 'filter_state', '', 'word');
        $filter_order       = $application->getUserStateFromRequest($option.'filter_order', 'filter_order', 'a.name', 'cmd' );
        $filter_order_Dir   = $application->getUserStateFromRequest($option.'filter_order_Dir', 'filter_order_Dir', '', 'word');
        $search             = $application->getUserStateFromRequest($option.'search', 'search', '', 'string' );
        $search             = JString::strtolower( $search );
        $where = array();


        if ($search) {
            $where[] = 'LOWER(a.name) LIKE '.$db->Quote('%'.$db->getEscaped( $search, true ).'%', false );
        }
        if ( $filter_state ) {
          if ( $filter_state == 'P' ) {
            $where[] = 'a.published = 1';
          } else if ($filter_state == 'U' ) {
            $where[] = 'a.published = 0';
          }
        }

         $where = ( count( $where ) ? ' WHERE '. implode( ' AND ',$where ) : '' );
         return $where;
    }

    function _buildContentOrderBy()
    {
        $application= JFactory::getApplication();
        $option = JRequest::getCmd( 'option').'-listings';

        $filter_order     = $application->getUserStateFromRequest( $option.'filter_order', 'filter_order', 'a.ordering', 'cmd' );
        $filter_order_Dir = $application->getUserStateFromRequest( $option.'filter_order_Dir',  'filter_order_Dir', '', 'word' );

        if ($filter_order == 'a.ordering'){
                $orderby 	= ' ORDER BY a.ordering '.$filter_order_Dir;
        } else {
                $orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , a.ordering ';
        }

        return $orderby;
    }

    
    function getSimplelistingLists($id)
    {
        $query = 'SELECT a.*,
        u.name as `username`, u.email as `email`,
        t.name as `type`, ca.name as `category`, l.name as `layout`,
        cd.telephone as `tel`, cd.mobile `mobile`, cd.fax as `fax`, cd.state `usercountry`,cd.misc `misc`
        FROM '.$this->_table_prefix.' AS a
        LEFT JOIN '.$this->_table_prefix.'_types AS t ON t.id = a.type_id
        LEFT JOIN '.$this->_table_prefix.'_categories AS ca ON ca.id = a.category_id
        LEFT JOIN '.$this->_table_prefix.'_layouts AS l ON l.id = a.layout_id
        LEFT JOIN '.$this->_table_prefix.'_facilities AS fa ON fa.id = a.facilities
        LEFT JOIN #__users AS u ON u.id = a.create_by
        LEFT JOIN #__contact_details AS cd ON cd.user_id = a.create_by
        WHERE a.id = '.$id;
        $db = $this->getDBO();
        $db->setQuery($query);
        $simplelisting = $db->loadObject();
        if ($simplelisting === null)
        JError::raiseError(500, 'Simple Listing with ID: '.$id.' not found.');
        else
        return $simplelisting;
    }

    function getNewSimplelisting()
    {
        $simplelistingTableRow =& $this->getTable('simplelisting');
        $simplelistingTableRow->id = 0;
        $simplelistingTableRow->simplelisting = null;
        return $simplelistingTableRow;
    }
    
    function saveSimplelisting($simplelisting)
    {
        $simplelistingTableRow =& $this->getTable('simplelisting');
        $simplelistingTableRow->reset();
        $simplelistingTableRow->reorder();
        $simplelistingTableRow->set( 'ordering', $simplelistingTableRow->getNextOrder());


        if (!$simplelistingTableRow->bind($simplelisting)) {
                JError::raiseError(500, JText::_('ERROR_BINDING_DATA_MSG'));
                return false;
        }

        if (!$simplelistingTableRow->check()) {
                JError::raiseError(500, JText::_('INVALID_DATA_MSG'));
                return false;
        }

        if (!$simplelistingTableRow->store()) {
                $errorMessage = $simplelistingTableRow->getError();
                JError::raiseError(500, JText::_('ERROR_BINDING_DATA_MSG').$errorMessage);
                return false;
        }
        return true;

    }
    
    function deleteSimplelisting($arrayIDs)
    {
        $gallery_num = implode(',',$arrayIDs);
        $item_gallery_dir = JPATH_ROOT .DS . 'components' . DS . 'com_simplelisting'.DS.'images'.DS.'gallery' . DS . $gallery_num;

        $query = "DELETE FROM '.$this->_table_prefix.', '.$this->_table_prefix.'_favourite
        USING '.$this->_table_prefix.'
        LEFT JOIN '.$this->_table_prefix.'_favourite ON '.$this->_table_prefix.'.id = '.$this->_table_prefix.'_favourite.simplelisting_id
        WHERE '.$this->_table_prefix.'.id IN (".implode(',', $arrayIDs).")";
        $db = $this->getDBO();
        $db->setQuery($query);
        if (!$db->query()){
                $errorMessage = $this->getDBO()->getErrorMsg();
                JError::raiseError(500, JText::_('ERROR_DELETING_ITEM_MSG').$errorMessage);
        }
        if ( JFolder::exists($item_gallery_dir) ) {JFolder::delete($item_gallery_dir); }
    }
    
    function uploadFile($file, $id) {
        $base_upload_dir = JPATH_ROOT.DS . 'components' . DS . 'com_simplelisting'.DS.'images'.DS.'gallery';
         if ( !JFolder::exists($base_upload_dir) ) { JFolder::create($base_upload_dir); }
         
        $upload_dir = $base_upload_dir . DS . $id;
        if ( !JFolder::exists($upload_dir) ) { JFolder::create($upload_dir); }
        
		$filename = JPath::clean(strtolower('main.jpg'));//Make the filename unique
        $filepath = $upload_dir.DS.$filename;//specific path of the file
        $allowed = array('image/jpeg', 'image/png', 'image/gif', 'image/JPG', 'image/jpg', 'image/pjpeg', 'images/x-png', 'images/PNG');
              
        if (!in_array($file['type'], $allowed)) //To check if the file are image file
        {
                echo "<script> alert('The file you are trying to upload is not supported.');
              window.history.back();</script>\n";
                exit;
        }
        else
        {
               $ext = JFile::getExt($file['name']);//Get extension of the file
                  
               switch ($ext)
               {
                 case 'jpeg':
                 case 'pjpeg':
                 case 'JPG':
                 case 'jpg':
                 $src = ImageCreateFromJpeg($file['tmp_name']);
                 break;

                 case 'png':
                 case 'PNG':
                 case 'x-png':
                 $src = ImageCreateFromPng($file['tmp_name']);
                 break;
                  
                 case 'gif':
                 $src = ImageCreateFromGif($file['tmp_name']);
                 break;
                     
               }
                  
                list($width,$height)=getimagesize($file['tmp_name']);
                $newwidth=400;//set file width to 600
                $newheight=($height/$width)*400;//the height are set according to ratio
                $tmp=imagecreatetruecolor($newwidth,$newheight);
                imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);//resample the image
                 
                switch ($ext)
               {
                  case 'jpeg':
                  case 'pjpeg':
                  case 'JPG':
                  case 'jpg':
                  $statusupload = imagejpeg($tmp,$filepath,100);//upload the image
                  break;
                     
                  case 'png':
                  case 'PNG':
                  case 'x-png':
                  $statusupload =  imagepng($tmp,$filepath,8);//upload the image
                  break;
                     
                 case 'gif':
                  $statusupload = imagegif($tmp,$filepath,100);//upload the image
                  break;
                     
               }

            chmod($filepath , 0777);
            
        }
		
	}
    
    function uploadFiles($file, $id) {
        $base_upload_dir = JPATH_ROOT.DS . 'components' . DS . 'com_simplelisting'.DS.'images'.DS.'gallery';
         if ( !JFolder::exists($base_upload_dir) ) { JFolder::create($base_upload_dir); }
         
        $upload_dir = $base_upload_dir . DS . $id . DS . 'second';
        if ( !JFolder::exists($upload_dir) ) { JFolder::create($upload_dir); }
        
        
        for($i=0;$i<count($file['name']);$i++) {
        $datetimes = date('Ymd-His');
        $filename = JPath::clean(strtolower($datetimes.'.jpg'));
        $filepath = $upload_dir.DS.$filename;//specific path of the file
        $allowed = array('image/jpeg', 'image/png', 'image/gif', 'image/JPG', 'image/jpg', 'image/pjpeg', 'images/x-png', 'images/PNG');
       
            if (!in_array($file['type'][$i], $allowed)) //To check if the file are image file
            {
                    echo "<script> alert('The file you are trying to upload is not supported.');
                  window.history.back();</script>\n";
                    exit;
            }
           
            else
            {
                   $ext = JFile::getExt($file['name'][$i]);//Get extension of the file
                      
                   switch ($ext)
                   {
                      case 'jpeg':
                      case 'pjpeg':
                      case 'JPG':
                      case 'jpg':
                         $src = ImageCreateFromJpeg($file['tmp_name'][$i]);
                         break;
                      
                      case 'png':
                      case 'PNG':
                      case 'x-png':
                         $src = ImageCreateFromPng($file['tmp_name'][$i]);
                         break;
                      
                      case 'gif':
                         $src = ImageCreateFromGif($file['tmp_name'][$i]);
                         break;
                         
                   }
                      
                    list($width,$height)=getimagesize($file['tmp_name'][$i]);
                    $newwidth=400;//set file width to 600
                    $newheight=($height/$width)*400;//the height are set according to ratio
                    $tmp=imagecreatetruecolor($newwidth,$newheight);
                    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);//resample the image
                     
                    switch ($ext)
                   {
                      case 'jpeg':
                      case 'pjpeg':
                      case 'JPG':
                      case 'jpg':
                      $statusupload = imagejpeg($tmp,$filepath,100);//upload the image
                      break;
                         
                      case 'png':
                      case 'PNG':
                      case 'x-png':
                      $statusupload =  imagepng($tmp,$filepath,8);//upload the image
                      break;
                         
                     case 'gif':
                      $statusupload = imagegif($tmp,$filepath,100);//upload the image
                      break;
                         
                   }

                chmod($filepath , 0777);
                
            }
        
        }
        
    }
    
    function deleteFile($id)
    {
        $path = JPATH_ROOT.'/components/com_simplelisting/images/gallery/'.$id.'/';
        $file = $path.'main.jpg';
        chmod($file , 0777);
        JFile::delete($file);  
    }
    
    function deleteFiles($id, $image)
    {
	$base_upload_dir = JPATH_ROOT.'/components/com_simplelisting/images/gallery/'.$id.'/second/';
        $file = $base_upload_dir.$image;
        chmod($file , 0777);
        JFile::delete($file);
        $image = JFolder::files( $base_upload_dir );
        if(empty($image)){
            JFolder::delete($base_upload_dir);
        }
    }
    
   
    function publish($cid = array(), $publish=1)
    {
        if (count( $cid ))
        {
        $cids = implode( ',', $cid );

        $query = 'UPDATE '.$this->_table_prefix
                . ' SET published = ' . intval( $publish )
                . ' WHERE id IN ( '.$cids.' )'
        ;
        $db = $this->getDBO();
        $db->setQuery($query);
            if (!$db->query()){
                    $errorMessage = $this->getDBO()->getErrorMsg();
                    JError::raiseError(500,  JText::_('ERROR_UPDATING_MSG').$errorMessage);
            }
        }
    }
}
?>
